<template>
  <basic-container>
    <el-form ref="ruleForm"
             :model="ruleForm"
             :rules="rules"
             label-width="100px"
             class="demo-ruleForm">
      <el-tabs tab-position="left"
               v-model="activeName">
        <el-tab-pane label="基本信息"
                     name="baseInfo">
          <el-col :span="6">
            <avue-form ref="baseForm"
                       v-model="baseForm"
                       :option="baseOption"
                       @submit="submitBaseForm"
                       @reset-change="resetForm">
            </avue-form>
          </el-col>
        </el-tab-pane>
        <el-tab-pane label="账号密码"
                     name="usernamePassword">
          <el-form-item label="用户名"
                        prop="username">
            <el-col :span="5">
              <el-input v-model="ruleForm.username"
                        disabled />
            </el-col>
          </el-form-item>
          <el-form-item label="原密码"
                        prop="originPassword">
            <el-col :span="5">
              <el-input v-model="ruleForm.originPassword"
                        placeholder="请输入原密码" />
            </el-col>
          </el-form-item>
          <el-form-item label="新密码"
                        prop="newPassword">
            <el-col :span="5">
              <el-input v-model="ruleForm.newPassword"
                        placeholder="请输入新密码" />
            </el-col>
          </el-form-item>
          <el-form-item label="确认密码"
                        prop="newPasswordConfirm">
            <el-col :span="5">
              <el-input v-model="ruleForm.newPasswordConfirm"
                        placeholder="请确认新密码" />
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-col :span="5">
              <el-button type="primary"
                         icon="el-icon-check"
                         @click="submitPassWordForm()">修改密码</el-button>
              <el-button @click="resetForm()"
                         icon="el-icon-delete">清空</el-button>
            </el-col>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="绑定手机"
                     name="phone">
          <el-form-item label="手机号码"
                        prop="phone">
            <el-col :span="5">
              <el-input v-model="ruleForm.phone"
                        placeholder="请输入手机号码" />
            </el-col>
          </el-form-item>
          <el-form-item label="手机验证码"
                        prop="phoneCode">
            <el-col :span="5">
              <el-input v-model="ruleForm.phoneCode"
                        size="small"
                        auto-complete="off"
                        placeholder="验证码">
                <template slot="append">
                  <span :class="[{display:phoneMsgKey}]"
                        class="msg-text"
                        @click="sendPhoneCode">{{ phoneMsgText }}</span>
                </template>
              </el-input>
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-col :span="5">
              <el-button type="primary"
                         icon="el-icon-check"
                         @click="submitPhoneForm()">绑定手机</el-button>
              <el-button icon="el-icon-delete"
                         @click="resetForm()">清空</el-button>
            </el-col>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="绑定邮箱"
                     name="email">
          <el-form-item label="邮箱"
                        prop="email">
            <el-col :span="5">
              <el-input v-model="ruleForm.email"
                        placeholder="请输入邮箱" />
            </el-col>
          </el-form-item>
          <el-form-item label="邮箱验证码"
                        prop="emailCode">
            <el-col :span="5">
              <el-input v-model="ruleForm.emailCode"
                        size="small"
                        auto-complete="off"
                        placeholder="验证码">
                <template slot="append">
                  <span :class="[{display:emailMsgKey}]"
                        class="msg-text"
                        @click="sendEmailCode">{{ emailMsgText }}</span>
                </template>
              </el-input>
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-col :span="5">
              <el-button type="primary"
                         icon="el-icon-check"
                         @click="submitEmailForm()">绑定邮箱</el-button>
              <el-button @click="resetForm()"
                         icon="el-icon-delete">清空</el-button>
            </el-col>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>
  </basic-container>
</template>

<script>
const
  EMAIL_MSGINIT = "邮箱验证码",
  PHONE_MSGINIT = "手机验证码",
  MSGSCUCCESS = "${time}秒后重发",
  MSGTIME = 60;

import { mapState } from "vuex";
import store from "@/store";
import { isvalidatemobile, validateEmail } from "@/util/validate";
import { selfEdit, editPassword, bindPhone, bindEmail } from "@/api/admin/user";
import { sendCode } from '@/api/common/code'
import { encryptAES } from '@/util/util'

export default {
  name: 'UserInfo',
  data () {
    return {
      emailMsgText: EMAIL_MSGINIT,
      emailMsgTime: MSGTIME,
      emailMsgKey: false,
      phoneMsgText: PHONE_MSGINIT,
      phoneMsgTime: MSGTIME,
      phoneMsgKey: false,
      activeName: 'baseInfo',
      baseForm: {
        avatar: '',
        nickname: "",
      },
      ruleForm: {
        username: "",
        originPassword: "",
        newPassword: "",
        newPasswordConfirm: "",
        phone: "",
        phoneCode: "",
        email: "",
        emailCode: "",
      },
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 11, max: 11, message: '长度在 11 个字符', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              let result = isvalidatemobile(value)
              if (result[0]) {
                callback(new Error(result[1]));
              } else {
                callback();
              }
            }, trigger: 'blur'
          }],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (validateEmail(value)) {
                callback()
              } else {
                callback(new Error('邮箱格式有误'))
              }
            }, trigger: 'blur'
          }],
        originPassword: [{ required: true, min: 6, message: "原密码不少于6位", trigger: "blur" }],
        newPassword: [{ required: true, min: 6, message: "新密码不少于6位", trigger: "blur" }],
        newPasswordConfirm: [
          { required: true, min: 6, message: "新密码不少于6位", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (this.ruleForm.originPassword !== "") {
                if (value !== this.ruleForm.newPassword) {
                  callback(new Error("两次输入密码不一致!"));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            }, trigger: "blur"
          },
        ],
        phoneCode: [{ required: true, min: 6, max: 6, message: "验证码长度为6位", trigger: "blur" }],
        emailCode: [{ required: true, min: 6, max: 6, message: "验证码长度为6位", trigger: "blur" }]
      },
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
    baseOption () {
      return {
        submitText: '保存资料',
        column: [{
          label: "头像",
          prop: "avatar",
          type: 'upload',
          accept: 'image/png,image/jpeg,image/jpg',
          listType: 'picture-img',
          loadText: '头像上传中、请稍等',
          tip: '请选择头像上传',
          span: 24,
          propsHttp: {
            res: 'data'
          },
          action: store.getters.avatarAction,
          rules: [{ required: true, message: "请上传头像", trigger: "blur" }]
        }, {
          label: '昵称',
          prop: 'nickname',
          span: 24,
          rules: [{ required: true, message: "请输入昵称", trigger: "blur" }]
        }]
      }
    }
  },
  created () {
    this.resetForm();
  },
  methods: {
    sendPhoneCode () {
      // 判断是否可以发送（时间限制）
      if (this.phoneMsgKey) return;
      // 发送验证码
      this.$refs.ruleForm.validateField("phone", (valid) => {
        if (!valid) {
          sendCode({
            scenes: 'bind',
            principal: this.ruleForm.phone,
            handlerType: 'phone'
          }).then((response) => {
            this.$message.success(response.data.message);
            this.phoneTimeCacl();
          });
        }
      });
    },
    sendEmailCode () {
      // 判断是否可以发送（时间限制）
      if (this.emailMsgKey) return;
      // 发送验证码
      this.$refs.ruleForm.validateField("email", (valid) => {
        if (!valid) {
          sendCode({
            scenes: 'bind',
            principal: this.ruleForm.email,
            handlerType: 'email'
          }).then((response) => {
            this.$message.success(response.data.message);
            this.emailTimeCacl();
          });
        }
      });
    },
    submitBaseForm () {
      selfEdit(this.baseForm).then((resp) => {
        this.$notify.success(resp.data.message);
        this.$store.dispatch("GetUserBaseInfo").then(() => {
          location.reload();
        });
      });
    },
    submitPassWordForm () {
      let validateFields = ['originPassword', 'newPassword', 'newPasswordConfirm']
      let flag = true
      validateFields.forEach(field => {
        this.$refs.ruleForm.validateField(field, (errorMessage) => {
          if (!!errorMessage) {
            flag = false
          }
        });
      })
      if (!flag)
        return
      editPassword({
        originPassword: encryptAES(this.ruleForm.originPassword),
        newPassword: encryptAES(this.ruleForm.newPassword)
      }).then((resp) => {
        this.$notify.success(resp.data.message);
        this.$store.dispatch("LogOut").then(() => {
          location.reload();
        });
      })
    },
    submitPhoneForm () {
      let validateFields = ['phone', 'phoneCode']
      let flag = true
      validateFields.forEach(field => {
        this.$refs.ruleForm.validateField(field, (errorMessage) => {
          if (!!errorMessage) {
            flag = false
          }
        });
      })
      if (!flag)
        return
      let { phone, phoneCode } = this.ruleForm
      bindPhone({ phone, code: phoneCode }).then((resp) => {
        this.$notify.success(resp.data.message);
        this.$store.dispatch("GetUserBaseInfo").then(() => {
          location.reload();
        });
      })
    },
    submitEmailForm () {
      let validateFields = ['email', 'emailCode']
      let flag = true
      validateFields.forEach(field => {
        this.$refs.ruleForm.validateField(field, (errorMessage) => {
          if (!!errorMessage) {
            flag = false
          }
        });
      })
      if (!flag)
        return
      let { email, emailCode } = this.ruleForm
      bindEmail({ email, code: emailCode }).then((resp) => {
        this.$notify.success(resp.data.message);
        this.$store.dispatch("GetUserBaseInfo").then(() => {
          location.reload();
        });
      })
    },
    resetForm () {
      // 基本信息
      this.baseForm.avatar = this.userInfo.avatar
      this.baseForm.nickname = this.userInfo.nickname
      // 账号密码
      this.ruleForm.username = this.userInfo.principal
      this.ruleForm.originPassword = undefined
      this.ruleForm.newPassword = undefined
      this.ruleForm.newPasswordConfirm = undefined
      // 手机号
      this.ruleForm.phone = this.userInfo.phone
      this.ruleForm.phoneCode = undefined
      // 邮箱
      this.ruleForm.email = this.userInfo.email
      this.ruleForm.emailCode = undefined
    },
    phoneTimeCacl () {
      // 计时避免重复发送
      this.phoneMsgText = MSGSCUCCESS.replace("${time}", this.phoneMsgTime);
      this.phoneMsgKey = true;
      const phoneTime = setInterval(() => {
        this.phoneMsgTime--;
        this.phoneMsgText = MSGSCUCCESS.replace("${time}", this.phoneMsgTime);
        console.log(this.phoneMsgTime)
        if (this.phoneMsgTime === 0) {
          this.phoneMsgTime = MSGTIME;
          this.phoneMsgText = PHONE_MSGINIT;
          this.phoneMsgKey = false;
          clearInterval(phoneTime);
        }
      }, 1000);
    },
    emailTimeCacl () {
      // 计时避免重复发送
      this.emailMsgText = MSGSCUCCESS.replace("${time}", this.emailMsgTime);
      this.emailMsgKey = true;
      const emailTime = setInterval(() => {
        this.emailMsgTime--;
        this.emailMsgText = MSGSCUCCESS.replace("${time}", this.emailMsgTime);
        if (this.emailMsgTime === 0) {
          this.emailMsgTime = MSGTIME;
          this.emailMsgText = EMAIL_MSGINIT;
          this.emailMsgKey = false;
          clearInterval(emailTime);
        }
      }, 1000);
    },
  },
};
</script>